#pragma once
#include <iostream>
#include <queue>
#include <vector>
#include <unistd.h>
#include "Thread.hpp"
#include "lockGuard.hpp"
#include "Task.hpp"
#include "log.hpp"
#define NUM 5
template <class T>
class ThreadPool
{
private:
    // 构造
    ThreadPool(int num = NUM) : _num(num)
    {
        // 初始化锁和条件变量
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_cond, nullptr);
    }
    ThreadPool(const ThreadPool<T> &tp) = delete;
    void operator=(const ThreadPool<T> &tp) = delete;

public:
    static ThreadPool<T> *gitinstance()
    {
        if (nullptr == instance)      //这样的意义：提高效率，减少加锁的时间
        {
            LockGuard lockguard(&Lock);
            if (nullptr == instance) // 如果对象为空创建对象
            {
                // std::cout<<"线程单例形成"<<std::endl;
                logMessage(Debug,"线程单例形成");
                instance = new ThreadPool<T>();
                instance->init();
                instance->start();
                instance->check();
            }
        }
        return instance;
    }
    bool isEmpty()
    {
        return _tasks.empty();
    }
    pthread_mutex_t *lock()
    {
        return &_mutex;
    }
    void Wait() // 等待
    {
        pthread_cond_wait(&_cond, &_mutex);
    }
    void wakeUp() // 唤醒
    {
        pthread_cond_signal(&_cond);
    }
    static void rountineTask(void *args)  //执行任务
    {
        // 1.线程分离--防止一个线程故障导致整个进程退出
        pthread_detach(pthread_self());
        ThreadPool<T> *tp = static_cast<ThreadPool<T> *>(args);

        while (true)
        {
            T t;
            {
                LockGuard lockguard(tp->lock());
                while (tp->isEmpty())
                {
                    tp->Wait();
                }
                t = tp->popTask();
            }
            // 执行任务
            t();
        }
    }

    // 初始化，创建一批线程--用类封装的线程
    void init()
    {
        for (int i = 0; i < _num; i++)
            _threads.push_back(Thread(i, rountineTask, this));
    }
     //运行线程
    void start()
    {
       
        for (auto &t : _threads)
            t.run();
    }
    void check()
    {
        for (auto &t : _threads)
            //cout << t.threadname() << "create running..." << endl;
                logMessage(Debug,"%screate running...",t.threadname().c_str());
    }
    T popTask()
    {
        T t = _tasks.front();
        _tasks.pop();
        return t;
    }
    void pushTask(T &in)
    {
        // 一个线程对临界资源访问需要加锁
        LockGuard lockguard(&_mutex);
        _tasks.push(in);
        wakeUp();
    }
    // 析构
    ~ThreadPool()
    {
        // 线程等待？-->需要线程等待吗？这个不是已经有线程分离了吗？
        for (auto &t : _threads)
        {
            t.join();
        }
        // 对锁和信号量进行销毁
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_cond);
    }

private:
    vector<Thread> _threads; // 创建一批线程
    int _num;
    std::queue<T> _tasks;   // 缓冲区--任务队列
    pthread_mutex_t _mutex; // 一把锁：保护临界资源
    pthread_cond_t _cond;   // 条件变量：防止饥饿问题

    static ThreadPool<T> *instance; // 创建懒汉单例
    static pthread_mutex_t Lock;    // 加锁保护单例
};

template <class T>
ThreadPool<T> *ThreadPool<T>::instance = nullptr;

template <class T>
pthread_mutex_t ThreadPool<T>::Lock = PTHREAD_MUTEX_INITIALIZER;